import axios from "axios";
import { Message } from "element-ui";
import qs from "querystring";
import iView from "iview";
import { LoadingBar } from "iview";
// get请求
async function get(url) {
  iView.LoadingBar.start();
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    const requestConfig = {
      headers: {
        Authorization: token
      }
    };
    const urlStr = `${url}`;
    const response = await axios.get(urlStr, requestConfig);
    iView.LoadingBar.finish();
    return response.data;
  } catch (error) {
    iView.LoadingBar.error();
    console.log("error", error);
    Message.error("服务器异常!");
  } finally {
  }
}
// post请求
async function post(url, param) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    const requestConfig = {
      headers: {
        "Content-Type": "application/json",
        responseType: "json",
        Authorization: token
      }
    };

    const urlStr = `${url}`;
    const paramStr = qs.stringify({ ...param });
    const response = await axios.post(
      urlStr,
      JSON.stringify(param),
      requestConfig
    );
    return response.data;
  } catch (error) {
    console.log("error", error);
    Message.error("服务器异常!");
  } finally {
  }
}
// postUrlencoded请求
async function postUrlencoded(url, param) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    // application/x-www-form-urlencoded; charset=UTF-8  application/json
    const requestConfig = {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        responseType: "json",
        Authorization: token
      }
    };

    const urlStr = `${url}`;
    const paramStr = qs.stringify({ ...param });
    const response = await axios.post(urlStr, paramStr, requestConfig);
    return response.data;
  } catch (error) {
    console.log("error", error);
    Message.error("服务器异常!");
  } finally {
  }
}
// formData-post请求
async function formDataType(url, param) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    const requestConfig = {
      headers: {
        "Content-Type": "multipart/form-data",
        responseType: "json",
        Authorization: token
      }
    };

    const urlStr = `${url}`;
    const paramStr = qs.stringify({ ...param });
    console.log("error", urlStr, param, requestConfig);
    const response = await axios.post(urlStr, param, requestConfig);
    return response.data;
  } catch (error) {
    console.log("error", error);
    Message.error("服务器异常!");
  } finally {
  }
}

export { get, post, formDataType, postUrlencoded };
